package com.powernode.controller;


import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("login")
public class LoginController {
    @Resource
    private UserService userService;

    /**
     * 登录
     * @param username
     * @param password
     * @param captcha
     * @param session
     * @return
     */
    @PostMapping("login.action")
    public Result login(String username, String password,String captcha, HttpSession session){
        //得到正确的验证码
        String trueCode = session.getAttribute(Constants.CAPTCHA_CODE_KEY).toString();
        //判断输入的验证码和正确的验证码是否一样
        if (trueCode.equalsIgnoreCase(captcha)){
            User user =this.userService.login(username, DigestUtils.md5DigestAsHex(password.getBytes()));
            if (user==null){
                return new Result(-1,"用户名或密码不正确");
            }
            //把用户数据放入到session
            user.setPassword("");
            session.setAttribute(Constants.SESSION_USER_KEY,user);
            return new Result(200,"登录成功");
        }else{
            return new Result(-1,"验证码不正确");
        }
    }

    @PostMapping("loginOut.action")
    public Result loginOut(HttpSession session){
        try {
            session.invalidate();
            return new Result(200,"退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1,"推出失败");
        }
    }
}
